package com.jsgt.greekfire.ui.main.launch

import android.Manifest
import androidx.core.app.ActivityCompat
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseActivity
import com.fhx.core.goToActivity
import com.jsgt.greekfire.R
import com.jsgt.greekfire.dao.viewmodel.WalletViewModel
import com.jsgt.greekfire.ui.main.MainAtrActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * author fhx
 * create time 2020/4/29 21:22
 **/
class LaunchActivity : BaseActivity() {
    private val walletViewModel: WalletViewModel by lazy {
        ViewModelProvider(this).get(WalletViewModel::class.java)
    }

    private var hasWallet = false

    override fun getLayoutId(): Int {
        return R.layout.activity_launch
    }

    override fun main() {
        requestPermission()

        walletViewModel.getAllIdentityWallet()?.observe(this, androidx.lifecycle.Observer {
            if (it.isNotEmpty()) {
                hasWallet = true
            }
        })
    }

    private fun requestPermission() {
        val permissions = arrayOf(
            Manifest.permission.READ_EXTERNAL_STORAGE
            , Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE
            , Manifest.permission.ACCESS_WIFI_STATE
        )
        //这是系统的方法
        ActivityCompat.requestPermissions(this, permissions, 1)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //先不管是否授予权限
        nextPage()
    }

    private fun nextPage() {
        if (isTaskRoot) {
            GlobalScope.launch(Dispatchers.Main) {
                delay(1000)
//                if (LOGIN_STATUS || WalletManager.getLocalWallets().size > 0) {
                if (hasWallet) {
                    goToActivity<MainAtrActivity>()
                } else {
                    goToActivity<LaunchTempActivity>()
                    overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
                }
                finish()
            }
        } else {
            finish()
        }
    }
}